import React, {useEffect, useState} from 'react'
import {Button, Space, Tag, message} from 'antd'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import BatchUpload from './components/BatchUpload'
import {downloadDocumentUrl} from '@/service/common/download'
import {getCompany} from '@/service/system/company'
import {modelSeriesFun, translateDataToTree} from '@/utils/common/index'
import {getXZCarTypeList} from '@/service/carMessage/list'
import Permissions from '@/components/Permissions'
// api调用
import {
	getTableList,
	checkBareCar,
	importBareCar,
	paabeegr,
} from '@/service/carMessage/inspection'
import {getNodeList} from '@/service/carMessage/archives'

import 'moment/locale/zh-cn'
// 字典
import {licenseProperty} from '../dict'
import {getHolderDictInfo} from '@/service/common'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

type IdType = {
	bareId: any // 弹框标题
	supplyId: any // 弹框是否可见
	supplyName: any
}
const renewalDom = (props: {
	user: {orgId: string | number; userName: string; userId: string}
	location: any
}) => {
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [tableList, setTableList] = useState<any[]>([])
	const [formData, setFormData] = useState<any[]>([])
	const [otherData, setOtherData] = useState<any>()
	const [orgSource, setOrgSource] = useState<any>([])
	const [carTypeList, setCarTypeList] = useState<any>([])

	// 导入
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [exportOrgId, setExportOrgId] = useState<any>()
	const [data, setData] = useState<IdType>()
	const [fileObj, setFileObj] = useState<any>()
	// 持有方数据
	const [holderDict, setHolderDict] = useState([])
	/** 获取持有方数据 */
	const getHolderDictInfoFun = () => {
		getHolderDictInfo({type: 'holder'}).then((res: any) => {
			if (res?.success) {
				setHolderDict(res?.data)
			}
		})
	}

	// 获取品牌车系
	const onCarTypeListFun = () => {
		getXZCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
	}

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({
			...params,
			...otherData,
		})
			.then((res: any) => {
				if (res?.success) {
					setTableList(() => res?.data?.records)
					setTotal(res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}
	// 获取表格数据
	useEffect(() => {
		onListFun()
	}, [params, otherData])

	useEffect(() => {
		getHolderDictInfoFun()
		onCarTypeListFun()
	}, [])

	// 列表
	const columns: any = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '供应商',
			dataIndex: 'supplyName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '招标编号',
			dataIndex: 'biddingNo',
			align: 'center',
			width: 140,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '采购申请单号',
			dataIndex: 'purchaseNo',
			align: 'center',
			width: 150,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '合同编号',
			dataIndex: 'contractNo',
			align: 'center',
			width: 150,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '品牌车系车型',
			dataIndex: 'fashionName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车辆性质',
			dataIndex: 'carProperty',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{licenseProperty?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '持有方',
			dataIndex: 'holderName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '入库城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '停车场名称',
			dataIndex: 'parkingName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '入库数量',
			dataIndex: 'warehouseNum',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '批量入库时间',
			dataIndex: 'warehouseTime',
			align: 'center',
			width: 200,
			render: (text: string) => {
				const dataTimeStr = text
					? moment(text).format('YYYY-MM-DD')
					: '--'
				return (
					<>
						<span>{dataTimeStr}</span>
					</>
				)
			},
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text: string, record: any) => (
				<div>
					<Permissions permissionID="amc_assetCenter_carMessage_inspection_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/inspection/view',
									query: {
										id: record.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_inspection_edit">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/inspection/edit',
									query: {
										id: record.id,
									},
								})
							}}>
							编辑
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_inspection_export">
						<Button
							type="link"
							size="small"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '121',
									queryDesc:
										'裸车验车入库导出,resourceId:121',
									queryParam: {bareId: record.id},
								})
							}}>
							导出
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_inspection_import">
						<Button
							type="link"
							size="small"
							onClick={() => {
								const d = {
									bareId: record.id,
									supplyId: record.supplyId,
									supplyName: record.supplyName,
								}
								setExportOrgId(() => record?.orgId)
								setData(() => d)
								setIsModalOpen(true)
							}}>
							导入
						</Button>
					</Permissions>
				</div>
			),
		},
	]

	const batchColumns: any = [
		{
			title: '车架号',
			dataIndex: 'vin',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '发动机号',
			dataIndex: 'engineNumber',
			align: 'center',
			width: 140,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车系名称',
			dataIndex: 'fashionName',
			align: 'center',
			width: 250,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车辆性质',
			dataIndex: 'carProperty',
			align: 'center',
			width: 150,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车辆颜色',
			dataIndex: 'colorName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '持有方',
			dataIndex: 'holderName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '公司名称',
			dataIndex: 'companyName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '城市名称',
			dataIndex: 'cityName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '生产日期',
			dataIndex: 'productionTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '错误信息',
			dataIndex: 'errorMsg',
			align: 'center',
			width: 200,
			fixed: 'right',
			render: (text: string) => <span>{text || '--'}</span>,
		},
	]

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}
	const nodeListFun = (orgId: any, callback: any) => {
		getNodeList({orgId})
			.then((res: any) => {
				if (res?.success) {
					callback(res?.data?.[0]?.processId)
				}
			})
			.catch((error: any) => {
				message.error(error.msg)
			})
	}

	useEffect(() => {
		onOrgFun()
	}, [props?.user?.orgId])

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [otherData])
	// 搜索
	const onFinish = (values: any) => {
		const time = values?.warehouseTimeStr
			? moment(values?.warehouseTimeStr).format('YYYY-MM-DD')
			: ''
		const searchData = Object.assign(values, {warehouseTimeStr: time})
		setOtherData(() => searchData)
	}
	// 重置
	const onReset = () => {
		setOtherData({})
	}

	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						key: 'supplyName',
						name: 'supplyName',
						label: '供应商名称',
					},
					{
						type: 'input',
						key: 'biddingNo',
						name: 'biddingNo',
						label: '招标编号',
					},
					{
						type: 'input',
						key: 'purchaseNo',
						name: 'purchaseNo',
						label: '采购申请单号',
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'input',
						key: 'contractNo',
						name: 'contractNo',
						label: '合同编号',
					},
					{
						type: 'select',
						key: 'fashionId',
						name: 'fashionId',
						label: '品牌车系车型',
						keys: 'id',
						title: 'fullName',
						items: [...carTypeList],
					},
					{
						type: 'select',
						key: 'carProperty',
						name: 'carProperty',
						label: '车辆性质',
						keys: 'key',
						title: 'label',
						items: [...licenseProperty],
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'select',
						label: '持有方',
						name: 'holderId',
						key: 'holderId',
						keys: 'value',
						title: 'valueName',
						items: [...holderDict],
					},
					{
						type: 'input',
						key: 'parkingName',
						name: 'parkingName',
						label: '停车场名称',
					},
					{
						type: 'time',
						key: 'warehouseTimeStr',
						subtype: 'date',
						name: 'warehouseTimeStr',
						label: '入库时间',
					},
				],
			},
		]
		setFormData(formItems)
	}, [orgSource, carTypeList])

	const importData = () => {
		nodeListFun(exportOrgId, (res: any) => {
			const formdata = new FormData()
			formdata.append('file', fileObj)
			formdata.append('bareId', data?.bareId)
			formdata.append('processId', res)
			formdata.append('supplyId', data?.supplyId)
			formdata.append('supplyName', data?.supplyName)
			importBareCar(formdata)
				.then((result: any) => {
					if (result?.success) {
						message.success(result.msg)
						setIsModalOpen(() => false)
						onListFun()
					}
				})
				.catch((error: any) => {
					message.error(error.msg)
				})
		})
	}

	// 获取导入失败表格数据
	const onTableList = (datas: any) =>
		paabeegr({...datas}).then((res: any) => {
			if (res?.success) {
				return res
			}
			return {}
		})

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Button
						type="primary"
						ghost
						size="small"
						onClick={() => {
							history.push({
								pathname: '/carMessage/inspection/add',
							})
						}}>
						新增入库计划
					</Button>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					kid="id"
					params={params}
					columns={columns}
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
				<BatchUpload
					isModalOpen={isModalOpen}
					setIsModalOpen={setIsModalOpen}
					setFileObj={setFileObj}
					importData={importData}
					onTableList={onTableList}
					fileNmae="file"
					uploadFileUrl={checkBareCar}
					columns={batchColumns}
					sourceId={6}
					templateType="裸车导入模板"
				/>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(renewalDom)
